﻿using UnityEngine;
using System.Collections;
using UnityEngine.Serialization;

namespace ProjectTW.Foliage
{
    public sealed class FoliageChunk : ChunkBase
    {
        // 细节对象实例，如果为空表示没有添加细节对象 
        [SerializeField]
        public FoliageInstanceObject AttachedFoliageInstance;
        
        // 是否添加细节对象
        [SerializeField]
        private bool m_FoliageInstancedAttached = false;

        /// <summary>
        /// 检查是否存在FoliageInstance附件对象，即是否存在渲染对象
        /// </summary>
        public bool IsFoliageInstanceAttached
        {
            get
            {
                if (!m_FoliageInstancedAttached)
                {
                    return false;
                }

                return AttachedFoliageInstance != null;
            }
        }

        public override void OnCreated()
        {
            base.OnCreated();
            SetCollider();
        }

        protected override void OnSizeChanged()
        {
            base.OnSizeChanged();
            SetCollider();
        }

        /// <summary>
        /// 根据当前是否有FoliageInstance附加对象，创建对应的附加对象
        /// </summary>
        /// <returns></returns>
        public FoliageInstanceObject GetOrCreateFoliageManagerInstance(bool poppulateHeights = true)
        {
            if (!IsFoliageInstanceAttached)
            {
                AttachedFoliageInstance = FoliageInstanceObject.CreateInstance(this, poppulateHeights);
                m_FoliageInstancedAttached = true;
            }

            return AttachedFoliageInstance;
        }

        /// <summary>
        /// 检查是否在Bounds
        /// </summary>
        /// <param name="normalizedPosition"></param>
        /// <param name="distance"></param>
        /// <returns></returns>
        public bool InBounds(Vector3 normalizedPosition, float distance)
        {
            Vector3 min = new Vector3(m_WorldPosition3D.x - distance, 0, m_WorldPosition3D.z - distance);
            Vector3 max = new Vector3(m_WorldPosition3D.x + Size.x + distance, 0, m_WorldPosition3D.z + Size.y + distance);

            return normalizedPosition.x >= min.x && normalizedPosition.z >= min.z && normalizedPosition.x <= max.x && normalizedPosition.z <= max.z;
        }

        private void SetCollider()
        {
            BoxCollider bc = GetComponent<BoxCollider>();

            if (bc == null)
            {
                bc = gameObject.AddComponent<BoxCollider>();
            }

            bc.center = new Vector3(Size.x / 2, 0.1f, Size.y / 2);
            bc.size = new Vector3(Size.x, 0.1f, Size.y);
            bc.isTrigger = true;
        }
    }
}
